package controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.Customer;
import pojo.User;
import service.CustomerService;
import service.UserService;

import java.util.List;
import java.util.Map;

@Controller()
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerService customerService;

    @PostMapping("queryCustomer")
    @ResponseBody
    public Customer queryCustomer(@RequestBody Customer customer){
        return customerService.queryCustomer(customer.getPhone());
    }

    @PostMapping("getAllCustomer")
    @ResponseBody
    public List<Customer> getAllCustomer(){
        return customerService.queryAllCustomer();
    }


    @PostMapping("addCustomer")
    @ResponseBody
    public int addCustomer(@RequestBody Customer customer){
        return customerService.addCustomer(customer);
    }

    @PostMapping("updateCustomer")
    @ResponseBody
    public int updateCustomer(@RequestBody Map<String, Object> map) throws JsonProcessingException {
        String oldPhone = (String) map.get("oldPhone");
        //map转对象
        ObjectMapper mapper = new ObjectMapper(); //转换器
        Customer customer=mapper.readValue( mapper.writeValueAsString(map.get("customer")), Customer.class);
        return customerService.updateCustomer(customer,oldPhone);
    }

    @PostMapping("deleteCustomer")
    @ResponseBody
    public int deleteCustomer(@RequestBody Customer customer){
        return customerService.deleteCustomer(customer.getPhone());
    }

}
